<template>
	<div class="hhw-check-page">
		<div class="page-title">固危废贮存场所点检</div>

		<div class="main-form">
			<FormItemRadio label="贮存情况" item-key="state" :required="true" v-model="formData.state" :dic-key="'ZQT_SSZCYC'" :readonly="isView" />

			<van-field v-if="formData.state === '0'" label="异常类型" :required="true" readonly :model-value="formData.exceptionTypeDes" />
			<van-field
				v-if="formData.state === '0'"
				label="异常说明"
				:required="true"
				type="textarea"
				autosize
				v-model="formData.exceptionDesc"
				:readonly="isView"
				placeholder="请输入"
			/>

			<FormItemDateTime
				:required="true"
				label="点检开始时间"
				item-key="beginTime"
				v-model="formData.beginTime"
				precision="minute"
				formatter="YYYY-MM-DD HH:mm:ss"
				:readonly="isView"
				:min-date="minDate"
				:max-date="maxDate"
				@confirm="onTimeConfirm"
			/>
			<FormItemDateTime
				:required="true"
				label="点检结束时间"
				item-key="endTime"
				v-model="formData.endTime"
				precision="minute"
				formatter="YYYY-MM-DD HH:mm:ss"
				:readonly="isView"
				:min-date="minDate"
				:max-date="maxDate"
				@confirm="onTimeConfirm"
			/>

			<van-field label="备注" type="textarea" autosize v-model="formData.remark" :readonly="isView" placeholder="请输入" />

			<FormFileUpload v-model="formData.fileData" :readonly="isView" :business-id="formData.id" big-type="ZQT_SSDJFJ_GWF" small-type="FJ" />
		</div>

		<div style="margin: 16px" v-if="!isView">
			<van-button block type="primary" @click="onSave">提交</van-button>
		</div>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { normalizeDateTime, isEndAfterOrEqual } from '@/utils/timeUtils'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getLocation } from '@/api'
import { addHhwCheck, getHhwDetail } from '@/api/facilityHhw'
import FormItemRadio from '@/components/form-item-radio'
import FormFileUpload from '@/components/form-file-upload'
import FormItemDateTime from '@/components/form-item-time/FormItemDateTime.vue'

export default {
	name: 'HhwFacilityCheck',
	components: { FormItemRadio, FormFileUpload, FormItemDateTime },
	setup() {
		const route = useRoute()
		const router = useRouter()
		const userStore = useUserStore()

		const isView = ref(route.query.isView === 'true')

		const formData = reactive({
			id: generateId(),
			pollutionSourceId: '',
			state: '',
			exceptionTypeDes: '固危废异常',
			exceptionType: '',
			exceptionDesc: '',
			beginTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
			endTime: dayjs().add(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
			longitude: '',
			latitude: '',
			remark: '',
			fileData: [],
		})

		// 时间范围：最早前2小时，最晚未来30天
		const minDate = dayjs().add(-2, 'hour').valueOf()
		const maxDate = dayjs().add(30, 'day').valueOf()

		function generateId() {
			return 'ID' + Math.random().toString(16).slice(2)
		}

		const init = async () => {
			// 尽可能早获取企业污染源 ID
			let cachedId = userStore.userInfo?.omDepts?.id
			if (!cachedId) {
				try {
					const user = await userStore.ensureLogin()
					cachedId = user?.omDepts?.id
				} catch (e) {
					console.error('获取用户信息失败', e)
				}
			}
			formData.pollutionSourceId = cachedId || ''
			if (!formData.pollutionSourceId) {
				console.warn('污染源ID未获取到，将导致提交缺失必填字段')
			}
			if (isView.value && route.query.id) {
				loadDetail(route.query.id)
			} else {
				try {
					const loc = await getLocation()
					formData.longitude = loc.longitude
					formData.latitude = loc.latitude
				} catch (e) {}
			}
		}

		const loadDetail = async (id) => {
			const res = await getHhwDetail(id)
			if (res.data) {
				Object.assign(formData, res.data)
			} else {
				showToast('未查询到数据')
			}
		}

		const onTimeConfirm = (obj) => {
			Object.assign(formData, obj)
		}

		const validate = () => {
			if (!formData.state) return showToast('请选择贮存情况'), false
			if (formData.state === '0') {
				if (!formData.exceptionDesc) return showToast('请输入异常说明'), false
			}
			if (!formData.fileData || formData.fileData.length === 0) return showToast('请上传附件'), false
			// 结束时间需 >= 开始时间
			if (dayjs(formData.endTime).isBefore(dayjs(formData.beginTime))) return showToast('结束时间不能早于开始时间'), false
			return true
		}

		const onSave = async () => {
			if (!validate()) return
			if (!formData.pollutionSourceId) return showToast('企业污染源ID缺失，无法提交'), false
			formData.beginTime = normalizeDateTime(formData.beginTime)
			formData.endTime = normalizeDateTime(formData.endTime)
			if (!isEndAfterOrEqual(formData.beginTime, formData.endTime)) {
				return showToast('结束时间不能早于开始时间')
			}
			formData.exceptionType = formData.state === '1' ? '' : 'WFYC'
			const res = await addHhwCheck(formData)
			if (res.code === '0') {
				showToast('提交成功')
				setTimeout(() => router.back(), 1200)
			}
		}

		onMounted(() => init())

		return {
			isView,
			formData,
			minDate,
			maxDate,
			onTimeConfirm,
			onSave,
		}
	},
}
</script>

<style lang="less" scoped>
.hhw-check-page {
	padding-bottom: 40px;
}
.page-title {
	font-size: 18px;
	font-weight: 600;
	padding: 16px;
}
.title-panel {
	font-weight: 600;
	margin: 8px 0 8px 8px;
}
.required {
	color: #f93333;
}
</style>
